package com.bjy.qa.agent.tester.handlers;

import com.alibaba.fastjson.JSONObject;
import com.bjy.qa.agent.enumtype.ConditionEnum;
import com.bjy.qa.agent.enumtype.RunStatus;
import com.bjy.qa.agent.model.HandleDes;
import com.bjy.qa.agent.tester.RunStepThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * else 步骤
 */
@Component
public class ElseHandler implements StepHandler {
    @Autowired
    private StepHandlers stepHandlers;

    /**
     * else 步骤
     * @param stepJSON  步骤 json
     * @param handleDes HandleDes 模型
     * @param thread RunStepThread
     * @return
     * @throws Throwable
     */
    @Override
    public HandleDes runStep(JSONObject stepJSON, HandleDes handleDes, RunStepThread thread) throws Throwable {
        if (thread.isStopped()) {
            return null;
        }

        // 取出 else 下所属的步骤，丢给 stepHandlers 处理
        JSONObject conditionStep = stepJSON.getJSONObject("step");
        List<JSONObject> steps = conditionStep.getJSONArray("childSteps").toJavaList(JSONObject.class);

        String stepDesc = conditionStep.getString("desc"); // 步骤描述

        // else 前应当必定有 if，如果前面的 if 执行成功，则直接跳过
        if (handleDes.getE() == null) {
            thread.getLogTool().sendStepLog(RunStatus.WARN, stepDesc, "「else」前的条件步骤执行通过，「else」跳过", "");
            return handleDes;
        }
        thread.getLogTool().sendStepLog(RunStatus.PASSED, stepDesc, "「else」前的条件步骤失败，开始执行「else」下的步骤", "");

        // 上述步骤有异常则取出 else 下的步骤，再次丢给 stepHandlers 处理
        if (handleDes.getE() != null) {
            handleDes.clear();
            for (JSONObject step : steps) {
                stepHandlers.runStep(handlerPublicStep(step), handleDes, thread);
            }
        }
        thread.getLogTool().sendStepLog(RunStatus.PASSED, stepDesc, "「else」步骤执行完毕", "");
        return handleDes;
    }

    /**
     * 获取步骤类型
     * @return
     */
    @Override
    public ConditionEnum getCondition() {
        return ConditionEnum.ELSE;
    }
}
